package cn.smartopen.aispace.utils;

import java.security.MessageDigest;  
import java.security.NoSuchAlgorithmException;  
import java.security.SecureRandom;
import java.time.Instant;  
  
public class Utils {  
  
    private static final String CHAR_POOL = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";  
    private static final SecureRandom random = new SecureRandom();  
  
    /**  
     * 生成指定长度的随机字符串  
     *  
     * @param length 字符串长度  
     * @return 指定长度的随机字符串  
     */  
    public static String generateRandomString(int length) {  
        if (length <= 0) {  
            throw new IllegalArgumentException("Length must be greater than 0");  
        }  
  
        StringBuilder sb = new StringBuilder(length);  
        for (int i = 0; i < length; i++) {  
            // 生成一个0到CHAR_POOL.length()-1之间的随机索引  
            int index = random.nextInt(CHAR_POOL.length());  
            // 从CHAR_POOL中取出对应索引的字符并添加到StringBuilder中  
            sb.append(CHAR_POOL.charAt(index));  
        }  
        return sb.toString();  
    }  

    /**  
     * 根据规则 "MD5(服务商主域名或服务器IP地址+服务商私钥签名)" 生成签名  
     *  
     * @param serviceDomainOrIp 服务商的主域名或服务器IP地址  
     * @param privateKeySignature 服务商的私钥签名（一个秘密字符串）  
     * @return 生成的MD5签名  
     */  
    public static String generateSignature(String serviceDomainOrIp, String privateKeySignature) {  
        try {  
            // 将服务商主域名或IP地址与私钥签名拼接  
            String concatenatedString = serviceDomainOrIp + privateKeySignature;  
              
            // 使用MD5算法对拼接后的字符串进行加密  
            MessageDigest md = MessageDigest.getInstance("MD5");  
            md.update(concatenatedString.getBytes());  
              
            // 将加密后的字节转换为十六进制字符串  
            byte[] digest = md.digest();  
            StringBuilder hexString = new StringBuilder();  
            for (byte b : digest) {  
                String hex = Integer.toHexString(0xff & b);  
                if(hex.length() == 1) hexString.append('0');  
                hexString.append(hex);  
            }  
              
            return hexString.toString();  
        } catch (NoSuchAlgorithmException e) {  
            throw new RuntimeException(e);  
        }  
    } 

    public static Long getCurrentTimeStamp() {
        long currentTimeSeconds = Instant.now().getEpochSecond();  
        return currentTimeSeconds;
    }


    public static void main(String[] args) {  
        String serviceDomainOrIp = "example.com";  
        String privateKeySignature = "secret_key";  

        String res = generateSignature(serviceDomainOrIp, privateKeySignature);
        System.out.println(res);  
        System.out.println(res.length());

        System.out.println(getCurrentTimeStamp());
    } 
  
}


